<template>
  <div class="auth-container">
    <div class="auth-card" style="width: 400px; padding: 40px;">
      <div class="auth-header">
        <div class="auth-logo">
          <el-icon><Lock /></el-icon>
        </div>
        <h1 class="auth-title">电子病历系统</h1>
      </div>
      
      <!-- 传统登录表单 -->
      <el-form 
        :model="loginForm" 
        class="auth-form"
        @submit.prevent="handleLogin"
      >
        <el-form-item>
          <el-input 
            v-model="loginForm.username" 
            placeholder="请输入用户名"
            prefix-icon="User"
            size="large"
          />
        </el-form-item>
        
        <el-form-item>
          <el-input 
            v-model="loginForm.password" 
            type="password" 
            placeholder="请输入密码"
            prefix-icon="Lock"
            show-password
            size="large"
          />
        </el-form-item>
        
        <el-form-item>
          <el-select 
            v-model="loginForm.role" 
            placeholder="请选择身份"
            size="large"
          >
            <el-option label="患者" value="patient" />
            <el-option label="医生" value="doctor" />
            <el-option label="医院管理员" value="admin" />
          </el-select>
        </el-form-item>
        
        <el-form-item>
          <el-button 
            type="primary" 
            class="auth-btn"
            native-type="submit"
            :loading="loading"
          >
            登录
          </el-button>
        </el-form-item>
      </el-form>
      
      <!-- 钱包登录部分 -->
      <div class="wallet-login-section">
        <div class="divider">
          <span class="divider-text">或</span>
        </div>
        
        <el-button 
          class="wallet-connect-btn"
          @click="connectWallet"
          :loading="walletConnecting"
          :disabled="walletConnected"
        >
          <span v-if="!walletConnected">使用 MetaMask 登录</span>
          <span v-else>已连接: {{ truncatedWalletAddress }}</span>
        </el-button>
        
        <el-button 
          v-if="walletConnected"
          class="wallet-login-btn"
          type="primary"
          @click="handleWalletLogin"
          :loading="walletLoggingIn"
        >
          确认钱包登录
        </el-button>
      </div>
      
      <div class="auth-footer">
        <div class="register-link">
          <span>还没有账号？</span>
          <el-link type="primary" @click="$router.push('/register')">立即注册</el-link>
        </div>
        <el-link type="primary" @click="$router.push('/Reset')">忘记密码？</el-link>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/store'
import { Lock } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

const authStore = useAuthStore()
const router = useRouter()

// 传统登录表单数据
const loginForm = ref({
  username: '',
  password: '',
  role: 'patient'
})

// 传统登录状态
const loading = ref(false)

// 钱包登录相关状态
const walletConnecting = ref(false)
const walletLoggingIn = ref(false)

// 使用store中的计算属性
const walletConnected = computed(() => authStore.walletConnected)
const truncatedWalletAddress = computed(() => {
  const address = authStore.blockchainAccount
  if (!address) return ''
  return `${address.substring(0, 6)}...${address.substring(38)}`
})

// 连接钱包
const connectWallet = async () => {
  walletConnecting.value = true
  
  try {
    const success = await authStore.initWeb3()
    if (!success) {
      ElMessage.error('连接钱包失败')
    }
  } catch (error) {
    console.error('连接钱包错误:', error)
    ElMessage.error(error.message || '连接钱包时出错')
  } finally {
    walletConnecting.value = false
  }
}

// 处理传统登录
const handleLogin = async () => {
  if (!loginForm.value.username) {
    ElMessage.error('请输入用户名')
    return
  }
  
  if (!loginForm.value.password) {
    ElMessage.error('请输入密码')
    return
  }
  
  if (!loginForm.value.role) {
    ElMessage.error('请选择身份')
    return
  }
  
  loading.value = true
  
  try {
    await authStore.login({
      username: loginForm.value.username,
      password: loginForm.value.password,
      role: loginForm.value.role
    })
    
    router.push(`/dashboard/${loginForm.value.role}`)
  } catch (error) {
    ElMessage.error(error.message || '登录失败，请稍后再试')
  } finally {
    loading.value = false
  }
}

// 处理钱包登录
const handleWalletLogin = async () => {
  if (!walletConnected.value) {
    ElMessage.error('请先连接钱包')
    return
  }

  walletLoggingIn.value = true
  
  try {
    await authStore.walletLogin('patient') // 钱包登录默认设为患者
    ElMessage.success('钱包登录成功')
    router.push('/dashboard/patient')
  } catch (error) {
    console.error('钱包登录错误:', error)
    ElMessage.error(error.message || '钱包登录失败')
  } finally {
    walletLoggingIn.value = false
  }
}

// 组件卸载时断开钱包连接
onUnmounted(() => {
  if (walletConnected.value) {
    authStore.disconnectWallet()
  }
})
</script>

<style scoped>
.auth-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f5f7fa;
}

.auth-card {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.auth-header {
  text-align: center;
  margin-bottom: 30px;
}

.auth-logo {
  width: 80px;
  height: 80px;
  margin: 0 auto 15px;
  background: #000;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.auth-logo .el-icon {
  font-size: 36px;
  color: #00c0a5;
}

.auth-title {
  font-size: 24px;
  font-weight: 600;
  color: #000;
  margin: 0;
}

.auth-form {
  margin-bottom: 20px;
}

.auth-btn {
  width: 100%;
  height: 45px;
  font-size: 16px;
  background-color: #1e5799;
  border: none;
  transition: background-color 0.3s;
}

.auth-btn:hover {
  background-color: #163f70;
}

.auth-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 10px;
}

.register-link {
  display: flex;
  align-items: center;
  gap: 5px;
  font-size: 14px;
  color: #606266;
}

.auth-footer .el-link {
  font-size: 14px;
}

/* 钱包登录部分样式 */
.wallet-login-section {
  margin: 25px 0;
}

.divider {
  display: flex;
  align-items: center;
  margin: 20px 0;
  color: #8c8c8c;
}

.divider::before,
.divider::after {
  content: "";
  flex: 1;
  border-bottom: 1px solid #dcdfe6;
}

.divider-text {
  padding: 0 15px;
  font-size: 14px;
}

.wallet-connect-btn {
  width: 100%;
  height: 45px;
  margin-bottom: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  background-color: #f8f9fa;
  border: 1px solid #dcdfe6;
}

.wallet-connect-btn:hover {
  background-color: #f1f3f5;
}

.wallet-icon {
  width: 24px;
  height: 24px;
}

.wallet-login-btn {
  width: 100%;
  height: 45px;
  font-size: 16px;
}
</style>